package org.base23.video.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.base23.video.domain.dto.*;
import org.base23.video.service.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.ArrayList;

/**
 * 视频分析编排服务实现
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class VideoAnalysisOrchestrationServiceImpl implements VideoAnalysisOrchestrationService {

    private final VideoAnalysisApiService videoAnalysisApiService;
    private final DetailedPostureAnalysisService detailedPostureAnalysisService;
    private final UserAnalysisResultService userAnalysisResultService;
    private final SmartVideoPlayerService smartVideoPlayerService;
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String performCompleteAnalysis(MultipartFile videoFile, Long userId, String sportType) {
        log.info("开始完整视频分析流程，用户ID: {}, 文件名: {}, 运动类型: {}", 
                userId, videoFile.getOriginalFilename(), sportType);

        String resultId = null;
        try {
            // 第一步：调用外部分析服务
            log.info("步骤1: 调用外部视频分析API");
            VideoAnalysisApiResponse apiResponse = videoAnalysisApiService.analyzeVideo(videoFile);
            
            if (apiResponse == null || apiResponse.getData() == null) {
                throw new RuntimeException("外部分析服务返回空响应");
            }

            resultId = apiResponse.getData().getResultId();
            log.info("外部分析完成，获得结果ID: {}", resultId);

            // 第二步：创建或更新数据库记录
            log.info("步骤2: 创建或更新数据库记录");
            createOrUpdateAnalysisRecord(userId, resultId, sportType, videoFile.getOriginalFilename(), apiResponse);

            // 第三步：获取详细分析数据
            log.info("步骤3: 获取外部分析的详细数据");
            VideoAnalysisResult.VideoAnalysisData analysisData = videoAnalysisApiService.getAnalysisResult(resultId);
            
            if (analysisData == null) {
                log.warn("无法获取详细分析数据，将状态标记为部分完成");
                updateAnalysisStatusSafely(userId, resultId, "PARTIAL_COMPLETED", "外部分析完成，但无法获取详细数据");
                return resultId;
            }

            // 第四步：AI详细分析
            log.info("步骤4: 执行AI详细分析");
            DetailedPostureAnalysis detailedAnalysis = detailedPostureAnalysisService.performDetailedAnalysis(sportType, analysisData);

            // 第五步：保存完整分析结果
            log.info("步骤5: 保存完整分析结果到数据库");
            saveCompleteAnalysisResultSafely(userId, resultId, analysisData, detailedAnalysis);

            // 第六步：生成智能播放器信息
            log.info("步骤6: 生成智能播放器信息");
            generateSmartPlayerInfoSafely(userId, resultId, analysisData, detailedAnalysis);

            log.info("完整视频分析流程完成，结果ID: {}，包含智能播放器信息", resultId);
            return resultId;

        } catch (Exception e) {
            log.error("视频分析流程失败，用户ID: {}, 错误: {}", userId, e.getMessage(), e);
            
            // 尝试记录失败状态
            if (resultId != null) {
                updateAnalysisStatusSafely(userId, resultId, "FAILED", "分析流程失败: " + e.getMessage());
            }
            
            throw new RuntimeException("视频分析流程失败: " + e.getMessage(), e);
        }
    }

    @Override
    public DetailedPostureAnalysis getCompleteAnalysisResult(Long userId, String resultId, String sportType) {
        log.info("获取完整分析结果，用户ID: {}, 结果ID: {}", userId, resultId);

        try {
            // 检查用户分析结果记录
            UserAnalysisResultDTO userResult = userAnalysisResultService.getAnalysisResultByUserIdAndResultId(userId, resultId);
            
            if (userResult == null) {
                throw new RuntimeException("未找到分析结果记录");
            }

            if (!"COMPLETED".equals(userResult.getStatus())) {
                log.info("分析尚未完成，当前状态: {}", userResult.getStatus());
                
                // 如果状态是ANALYZING，尝试获取最新结果
                if ("ANALYZING".equals(userResult.getStatus())) {
                    return tryGetLatestAnalysisResult(userId, resultId, sportType);
                }
                
                throw new RuntimeException("分析尚未完成，当前状态: " + userResult.getStatus());
            }

            // 如果已完成，从数据库中解析优化的分析数据
            if (userResult.getAnalysisData() != null) {
                try {
                    // 尝试解析优化的分析数据
                    OptimizedAnalysisData optimizedData = objectMapper.readValue(
                            userResult.getAnalysisData(), 
                            OptimizedAnalysisData.class
                    );
                    return convertOptimizedDataToDetailedAnalysis(optimizedData);
                } catch (Exception e) {
                    log.warn("解析优化分析数据失败，尝试解析原始数据: {}", e.getMessage());
                    try {
                        // 向后兼容：尝试解析原始数据格式
                        VideoAnalysisResult.VideoAnalysisData analysisData = objectMapper.readValue(
                                userResult.getAnalysisData(), 
                                VideoAnalysisResult.VideoAnalysisData.class
                        );
                        return detailedPostureAnalysisService.performDetailedAnalysis(sportType, analysisData);
                    } catch (Exception e2) {
                        log.warn("解析原始分析数据也失败，尝试重新获取: {}", e2.getMessage());
                    }
                }
            }

            // 如果数据库中没有详细数据，重新从外部API获取
            return tryGetLatestAnalysisResult(userId, resultId, sportType);

        } catch (Exception e) {
            log.error("获取完整分析结果失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取完整分析结果失败: " + e.getMessage(), e);
        }
    }

    @Override
    public String checkAnalysisStatus(Long userId, String resultId) {
        try {
            UserAnalysisResultDTO userResult = userAnalysisResultService.getAnalysisResultByUserIdAndResultId(userId, resultId);
            return userResult != null ? userResult.getStatus() : "NOT_FOUND";
        } catch (Exception e) {
            log.error("检查分析状态失败: {}", e.getMessage(), e);
            return "ERROR";
        }
    }

    /**
     * 创建或更新分析记录（安全版本，避免重复创建导致的事务回滚）
     */
    private void createOrUpdateAnalysisRecord(Long userId, String resultId, String sportType, 
                                            String videoFileName, VideoAnalysisApiResponse apiResponse) {
        try {
            // 首先检查是否已存在记录
            UserAnalysisResultDTO existingResult = null;
            try {
                existingResult = userAnalysisResultService.getAnalysisResultByUserIdAndResultId(userId, resultId);
            } catch (Exception e) {
                // 记录不存在，这是预期的情况
                log.debug("分析记录不存在，准备创建新记录: {}", e.getMessage());
            }
            
            if (existingResult == null) {
                // 创建新记录
                CreateAnalysisResultParam createParam = new CreateAnalysisResultParam();
                createParam.setUserId(userId);
                createParam.setResultId(resultId);
                createParam.setSportType(sportType);
                createParam.setVideoFileName(videoFileName);
                createParam.setStatus("ANALYZING");

                // 将外部API响应作为初始摘要保存
                if (apiResponse.getData() != null && apiResponse.getData().getSummary() != null) {
                    String initialSummary = String.format(
                        "外部分析完成 - 处理时间: %s, 总帧数: %d, 处理帧数: %d, FPS: %d",
                        apiResponse.getData().getProcessingTime(),
                        apiResponse.getData().getSummary().getTotalFrames(),
                        apiResponse.getData().getSummary().getFramesProcessed(),
                        apiResponse.getData().getSummary().getFps()
                    );
                    createParam.setSummary(initialSummary);
                }

                userAnalysisResultService.createAnalysisResult(createParam);
                log.info("分析记录创建成功，用户ID: {}, 结果ID: {}", userId, resultId);
            } else {
                // 记录已存在，更新状态为ANALYZING
                log.info("分析记录已存在，更新状态为ANALYZING，用户ID: {}, 结果ID: {}", userId, resultId);
                UpdateAnalysisResultParam updateParam = new UpdateAnalysisResultParam();
                updateParam.setId(existingResult.getId());
                updateParam.setStatus("ANALYZING");
                
                // 更新摘要
                if (apiResponse.getData() != null && apiResponse.getData().getSummary() != null) {
                    String initialSummary = String.format(
                        "重新分析中 - 处理时间: %s, 总帧数: %d, 处理帧数: %d, FPS: %d",
                        apiResponse.getData().getProcessingTime(),
                        apiResponse.getData().getSummary().getTotalFrames(),
                        apiResponse.getData().getSummary().getFramesProcessed(),
                        apiResponse.getData().getSummary().getFps()
                    );
                    updateParam.setSummary(initialSummary);
                }
                
                userAnalysisResultService.updateAnalysisResult(updateParam);
            }

        } catch (Exception e) {
            log.error("创建或更新分析记录失败，用户ID: {}, 结果ID: {}, 错误: {}", 
                     userId, resultId, e.getMessage(), e);
            // 不抛出异常，允许流程继续
        }
    }

    /**
     * 保存完整分析结果（安全版本）
     */
    private void saveCompleteAnalysisResultSafely(Long userId, String resultId, 
                                                VideoAnalysisResult.VideoAnalysisData analysisData,
                                                DetailedPostureAnalysis detailedAnalysis) {
        try {
            // 创建优化的分析数据，只保存改善建议和时间段信息
            OptimizedAnalysisData optimizedData = convertToOptimizedData(analysisData, detailedAnalysis);
            String optimizedDataJson = objectMapper.writeValueAsString(optimizedData);
            String summary = generateDetailedSummary(detailedAnalysis);
            
            // 计算数据大小和压缩率
            String originalDataJson = objectMapper.writeValueAsString(analysisData);
            int originalSize = originalDataJson.getBytes().length;
            int optimizedSize = optimizedDataJson.getBytes().length;
            double compressionRatio = originalSize > 0 ? (double) optimizedSize / originalSize : 0.0;
            
            // 保存优化数据
            userAnalysisResultService.completeAnalysis(userId, resultId, optimizedDataJson, summary);
            
            // 更新优化信息
            updateOptimizationInfo(userId, resultId, originalSize, optimizedSize, compressionRatio);
            
            log.info("优化分析结果保存成功，用户ID: {}, 结果ID: {}，数据压缩率: {:.2f}%, 原始大小: {}字节, 优化后: {}字节", 
                    userId, resultId, (1 - compressionRatio) * 100, originalSize, optimizedSize);

        } catch (Exception e) {
            log.error("保存完整分析结果失败，用户ID: {}, 结果ID: {}, 错误: {}", 
                     userId, resultId, e.getMessage(), e);
            updateAnalysisStatusSafely(userId, resultId, "FAILED", "保存分析结果失败: " + e.getMessage());
        }
    }

    /**
     * 更新分析状态（安全版本，不抛出异常）
     */
    private void updateAnalysisStatusSafely(Long userId, String resultId, String status, String errorMessage) {
        try {
            UserAnalysisResultDTO existingResult = userAnalysisResultService.getAnalysisResultByUserIdAndResultId(userId, resultId);
            if (existingResult != null) {
                UpdateAnalysisResultParam updateParam = new UpdateAnalysisResultParam();
                updateParam.setId(existingResult.getId());
                updateParam.setStatus(status);
                updateParam.setErrorMessage(errorMessage);
                userAnalysisResultService.updateAnalysisResult(updateParam);
                log.info("分析状态更新成功，用户ID: {}, 结果ID: {}, 状态: {}", userId, resultId, status);
            } else {
                log.warn("未找到分析记录，无法更新状态，用户ID: {}, 结果ID: {}", userId, resultId);
            }
        } catch (Exception e) {
            log.error("更新分析状态失败，用户ID: {}, 结果ID: {}, 错误: {}", 
                     userId, resultId, e.getMessage(), e);
            // 不抛出异常，确保不会影响上层调用
        }
    }

    /**
     * 更新分析状态（保留原有方法以兼容性）
     */
    private void updateAnalysisStatus(Long userId, String resultId, String status, String errorMessage) {
        updateAnalysisStatusSafely(userId, resultId, status, errorMessage);
    }

    /**
     * 尝试获取最新的分析结果
     */
    private DetailedPostureAnalysis tryGetLatestAnalysisResult(Long userId, String resultId, String sportType) {
        try {
            VideoAnalysisResult.VideoAnalysisData analysisData = videoAnalysisApiService.getAnalysisResult(resultId);
            if (analysisData != null) {
                DetailedPostureAnalysis detailedAnalysis = detailedPostureAnalysisService.performDetailedAnalysis(sportType, analysisData);
                
                // 异步保存结果
                saveCompleteAnalysisResultSafely(userId, resultId, analysisData, detailedAnalysis);
                
                // 异步生成智能播放器信息
                generateSmartPlayerInfoSafely(userId, resultId, analysisData, detailedAnalysis);
                
                return detailedAnalysis;
            }
        } catch (Exception e) {
            log.warn("尝试获取最新分析结果失败: {}", e.getMessage());
        }
        
        throw new RuntimeException("无法获取分析结果");
    }

    /**
     * 生成智能播放器信息（安全版本）
     */
    private void generateSmartPlayerInfoSafely(Long userId, String resultId, 
                                             VideoAnalysisResult.VideoAnalysisData analysisData,
                                             DetailedPostureAnalysis detailedAnalysis) {
        try {
            String videoUrl = "/api/video/play/" + resultId; // 构建视频URL
            smartVideoPlayerService.generatePlayerInfo(userId, resultId, videoUrl, analysisData, detailedAnalysis);
            log.info("智能播放器信息生成成功，用户ID: {}, 结果ID: {}", userId, resultId);
        } catch (Exception e) {
            log.error("生成智能播放器信息失败，用户ID: {}, 结果ID: {}, 错误: {}", 
                     userId, resultId, e.getMessage(), e);
            
            // 尝试更新播放器状态为失败
            try {
                smartVideoPlayerService.updatePlayerStatus(userId, resultId, "FAILED", 
                    "生成智能播放器信息失败: " + e.getMessage());
            } catch (Exception updateEx) {
                log.error("更新播放器失败状态也失败: {}", updateEx.getMessage(), updateEx);
            }
        }
    }

    /**
     * 生成详细摘要
     */
    private String generateDetailedSummary(DetailedPostureAnalysis analysis) {
        StringBuilder summary = new StringBuilder();
        summary.append("🏃 AI详细分析完成：");

        if (analysis.getMovementPhases() != null && !analysis.getMovementPhases().isEmpty()) {
            summary.append(String.format("识别到 %d 个运动阶段", analysis.getMovementPhases().size()));
        }

        if (analysis.getJointDetailAnalysis() != null && !analysis.getJointDetailAnalysis().isEmpty()) {
            summary.append(String.format("，完成 %d 个关节详细分析", analysis.getJointDetailAnalysis().size()));
        }

        if (analysis.getBiomechanicsAnalysis() != null) {
            summary.append("，包含完整生物力学评估");
        }

        if (analysis.getPersonalizedCoaching() != null) {
            summary.append("。已生成个性化教练指导建议");
        }

        summary.append("。");
        return summary.toString();
    }

    /**
     * 将原始分析数据转换为优化的数据结构
     * 只保存改善建议和时间段信息，排除逐帧数据
     */
    private OptimizedAnalysisData convertToOptimizedData(VideoAnalysisResult.VideoAnalysisData analysisData,
                                                        DetailedPostureAnalysis detailedAnalysis) {
        OptimizedAnalysisData optimizedData = new OptimizedAnalysisData();

        // 1. 设置视频摘要信息（不包含逐帧数据）
        if (analysisData != null && analysisData.getVideoInfo() != null) {
            OptimizedAnalysisData.VideoSummary videoSummary = new OptimizedAnalysisData.VideoSummary();
            videoSummary.setFps(analysisData.getVideoInfo().getFps() != null ? analysisData.getVideoInfo().getFps().doubleValue() : null);
            videoSummary.setTotalFrames(analysisData.getVideoInfo().getTotalFrames());
            if (analysisData.getVideoInfo().getFps() != null && analysisData.getVideoInfo().getTotalFrames() != null) {
                videoSummary.setDuration(analysisData.getVideoInfo().getTotalFrames().doubleValue() / analysisData.getVideoInfo().getFps().doubleValue());
            }
            optimizedData.setVideoSummary(videoSummary);
        }

        if (detailedAnalysis != null) {
            // 2. 设置整体评估
            optimizedData.setOverallAssessment(detailedAnalysis.getOverallAssessment());

            // 3. 转换运动阶段为改善信息
            if (detailedAnalysis.getMovementPhases() != null) {
                List<OptimizedAnalysisData.PhaseImprovement> phaseImprovements = new ArrayList<>();
                for (DetailedPostureAnalysis.MovementPhase phase : detailedAnalysis.getMovementPhases()) {
                    OptimizedAnalysisData.PhaseImprovement improvement = convertPhaseToImprovement(phase, analysisData);
                    if (improvement != null) {
                        phaseImprovements.add(improvement);
                    }
                }
                optimizedData.setPhaseImprovements(phaseImprovements);
            }

            // 4. 转换关节分析为改善信息
            if (detailedAnalysis.getJointDetailAnalysis() != null) {
                List<OptimizedAnalysisData.JointImprovement> jointImprovements = new ArrayList<>();
                for (DetailedPostureAnalysis.JointDetailAnalysis joint : detailedAnalysis.getJointDetailAnalysis()) {
                    OptimizedAnalysisData.JointImprovement improvement = convertJointToImprovement(joint);
                    if (improvement != null) {
                        jointImprovements.add(improvement);
                    }
                }
                optimizedData.setJointImprovements(jointImprovements);
            }

            // 5. 设置个性化指导建议（完整保留）
            optimizedData.setPersonalizedCoaching(detailedAnalysis.getPersonalizedCoaching());

            // 6. 设置训练计划（完整保留）
            optimizedData.setTrainingPlan(detailedAnalysis.getTrainingPlan());

            // 7. 设置生物力学分析（关键指标）
            optimizedData.setBiomechanicsAnalysis(detailedAnalysis.getBiomechanicsAnalysis());
        }

        return optimizedData;
    }

    /**
     * 将运动阶段转换为改善信息
     */
    private OptimizedAnalysisData.PhaseImprovement convertPhaseToImprovement(DetailedPostureAnalysis.MovementPhase phase,
                                                                           VideoAnalysisResult.VideoAnalysisData analysisData) {
        if (phase == null) return null;

        OptimizedAnalysisData.PhaseImprovement improvement = new OptimizedAnalysisData.PhaseImprovement();
        improvement.setPhaseName(phase.getPhaseName());
        improvement.setCurrentScore(phase.getPhaseScore());
        improvement.setCriticalPoints(phase.getCriticalPoints());

        // 转换帧范围为时间范围
        if (phase.getFrameRange() != null && analysisData != null && analysisData.getVideoInfo() != null) {
            Integer fps = analysisData.getVideoInfo().getFps();
            if (fps != null && fps > 0) {
                double startTime = phase.getFrameRange().getStartFrame().doubleValue() / fps.doubleValue();
                double endTime = phase.getFrameRange().getEndFrame().doubleValue() / fps.doubleValue();
                improvement.setTimeRange(new OptimizedAnalysisData.TimeRange(startTime, endTime));
            }
        }

        // 生成改善动作建议
        if (phase.getKeyActions() != null) {
            List<String> improvementActions = new ArrayList<>();
            for (DetailedPostureAnalysis.KeyAction action : phase.getKeyActions()) {
                if (action.getImprovement() != null && !action.getImprovement().trim().isEmpty()) {
                    improvementActions.add(action.getImprovement());
                }
            }
            improvement.setImprovementActions(improvementActions);
        }

        // 设置优先级（基于分数）
        if (phase.getPhaseScore() != null) {
            if (phase.getPhaseScore() < 60) {
                improvement.setPriority("HIGH");
                improvement.setTargetScore(80.0);
            } else if (phase.getPhaseScore() < 80) {
                improvement.setPriority("MEDIUM");
                improvement.setTargetScore(90.0);
            } else {
                improvement.setPriority("LOW");
                improvement.setTargetScore(95.0);
            }
        }

        return improvement;
    }

    /**
     * 将关节分析转换为改善信息
     */
    private OptimizedAnalysisData.JointImprovement convertJointToImprovement(DetailedPostureAnalysis.JointDetailAnalysis joint) {
        if (joint == null) return null;

        OptimizedAnalysisData.JointImprovement improvement = new OptimizedAnalysisData.JointImprovement();
        improvement.setJointName(joint.getJointName());
        improvement.setCurrentPerformance(joint.getCurrentPerformance());
        improvement.setTargetRange(joint.getOptimalRange());
        improvement.setSpecificAdvice(joint.getSpecificAdvice());

        // 生成问题描述
        if (joint.getCurrentPerformance() != null) {
            StringBuilder problemDesc = new StringBuilder();
            if (joint.getCurrentPerformance().getConsistency() != null && joint.getCurrentPerformance().getConsistency() < 0.7) {
                problemDesc.append("动作一致性不足；");
            }
            if (joint.getCurrentPerformance().getSmoothness() != null && joint.getCurrentPerformance().getSmoothness() < 0.7) {
                problemDesc.append("动作流畅性需要提高；");
            }
            if (joint.getCurrentPerformance().getEfficiency() != null && joint.getCurrentPerformance().getEfficiency() < 0.7) {
                problemDesc.append("动作效率偏低；");
            }
            improvement.setProblemDescription(problemDesc.toString());
        }

        // 设置风险等级
        if (joint.getCurrentPerformance() != null && joint.getCurrentPerformance().getRiskFactor() != null) {
            Double riskFactor = joint.getCurrentPerformance().getRiskFactor();
            if (riskFactor > 0.7) {
                improvement.setRiskLevel("HIGH");
                improvement.setImprovementTimeframe("1-2周");
            } else if (riskFactor > 0.4) {
                improvement.setRiskLevel("MEDIUM");
                improvement.setImprovementTimeframe("2-4周");
            } else {
                improvement.setRiskLevel("LOW");
                improvement.setImprovementTimeframe("4-8周");
            }
        }

        return improvement;
    }

    /**
     * 将优化的分析数据转换回DetailedPostureAnalysis
     * 用于从数据库读取时重构详细分析结果
     */
    private DetailedPostureAnalysis convertOptimizedDataToDetailedAnalysis(OptimizedAnalysisData optimizedData) {
        if (optimizedData == null) return null;

        DetailedPostureAnalysis detailedAnalysis = new DetailedPostureAnalysis();

        // 设置整体评估
        detailedAnalysis.setOverallAssessment(optimizedData.getOverallAssessment());

        // 转换阶段改善信息为运动阶段
        if (optimizedData.getPhaseImprovements() != null) {
            List<DetailedPostureAnalysis.MovementPhase> movementPhases = new ArrayList<>();
            for (OptimizedAnalysisData.PhaseImprovement improvement : optimizedData.getPhaseImprovements()) {
                DetailedPostureAnalysis.MovementPhase phase = convertImprovementToPhase(improvement);
                if (phase != null) {
                    movementPhases.add(phase);
                }
            }
            detailedAnalysis.setMovementPhases(movementPhases);
        }

        // 转换关节改善信息为关节分析
        if (optimizedData.getJointImprovements() != null) {
            List<DetailedPostureAnalysis.JointDetailAnalysis> jointAnalyses = new ArrayList<>();
            for (OptimizedAnalysisData.JointImprovement improvement : optimizedData.getJointImprovements()) {
                DetailedPostureAnalysis.JointDetailAnalysis joint = convertImprovementToJoint(improvement);
                if (joint != null) {
                    jointAnalyses.add(joint);
                }
            }
            detailedAnalysis.setJointDetailAnalysis(jointAnalyses);
        }

        // 设置其他完整保留的数据
        detailedAnalysis.setPersonalizedCoaching(optimizedData.getPersonalizedCoaching());
        detailedAnalysis.setTrainingPlan(optimizedData.getTrainingPlan());
        detailedAnalysis.setBiomechanicsAnalysis(optimizedData.getBiomechanicsAnalysis());

        return detailedAnalysis;
    }

    /**
     * 将阶段改善信息转换为运动阶段
     */
    private DetailedPostureAnalysis.MovementPhase convertImprovementToPhase(OptimizedAnalysisData.PhaseImprovement improvement) {
        if (improvement == null) return null;

        DetailedPostureAnalysis.MovementPhase phase = new DetailedPostureAnalysis.MovementPhase();
        phase.setPhaseName(improvement.getPhaseName());
        phase.setPhaseScore(improvement.getCurrentScore());
        phase.setCriticalPoints(improvement.getCriticalPoints());

        // 转换时间范围为帧范围（如果有视频信息的话，这里简化处理）
        if (improvement.getTimeRange() != null) {
            phase.setDuration(improvement.getTimeRange().getDuration());
        }

        // 重构关键动作
        if (improvement.getImprovementActions() != null) {
            List<DetailedPostureAnalysis.KeyAction> keyActions = new ArrayList<>();
            for (String action : improvement.getImprovementActions()) {
                DetailedPostureAnalysis.KeyAction keyAction = new DetailedPostureAnalysis.KeyAction();
                keyAction.setImprovement(action);
                keyActions.add(keyAction);
            }
            phase.setKeyActions(keyActions);
        }

        return phase;
    }

    /**
     * 将关节改善信息转换为关节分析
     */
    private DetailedPostureAnalysis.JointDetailAnalysis convertImprovementToJoint(OptimizedAnalysisData.JointImprovement improvement) {
        if (improvement == null) return null;

        DetailedPostureAnalysis.JointDetailAnalysis joint = new DetailedPostureAnalysis.JointDetailAnalysis();
        joint.setJointName(improvement.getJointName());
        joint.setCurrentPerformance(improvement.getCurrentPerformance());
        joint.setOptimalRange(improvement.getTargetRange());
        joint.setSpecificAdvice(improvement.getSpecificAdvice());

        return joint;
    }

    /**
     * 更新分析记录的优化信息
     */
    private void updateOptimizationInfo(Long userId, String resultId, int originalSize, int optimizedSize, double compressionRatio) {
        try {
            UserAnalysisResultDTO existingResult = userAnalysisResultService.getAnalysisResultByUserIdAndResultId(userId, resultId);
            if (existingResult != null) {
                UpdateAnalysisResultParam updateParam = new UpdateAnalysisResultParam();
                updateParam.setId(existingResult.getId());
                updateParam.setDataVersion("v2.0");
                updateParam.setIsOptimized(true);
                updateParam.setDataSizeBytes(optimizedSize);
                updateParam.setOriginalDataSizeBytes(originalSize);
                updateParam.setCompressionRatio(compressionRatio);
                updateParam.setDataType("OPTIMIZED_ANALYSIS");
                
                userAnalysisResultService.updateAnalysisResult(updateParam);
                log.info("优化信息更新成功，用户ID: {}, 结果ID: {}", userId, resultId);
            }
        } catch (Exception e) {
            log.error("更新优化信息失败，用户ID: {}, 结果ID: {}, 错误: {}", 
                     userId, resultId, e.getMessage(), e);
            // 不抛出异常，确保不会影响主流程
        }
    }
} 